package jmine.tec.web.servlet.cipher.impl;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jmine.tec.web.servlet.cipher.SecureCommunicationHandler;
import jmine.tec.web.servlet.cipher.challenge.Assertion;

/**
 * {@link CheckAssertionSecureCommunicationHandler} que liga com a comunicacao de criptografia simetrica
 * 
 * @author takeshi
 */
public class SymetricCheckAssertionSecureCommunicationHandler extends CheckAssertionSecureCommunicationHandler {

    /**
     * C'tor
     * 
     * @param challenge o {@link Assertion}
     * @param key a {@link PublicKey}
     * @param private1 a {@link PrivateKey}
     * @param chunkSize int
     * @param cipher {@link Cipher}
     */
    public SymetricCheckAssertionSecureCommunicationHandler(Assertion challenge, PublicKey key, PrivateKey private1, int chunkSize, Cipher cipher) {
        super(challenge, key, private1, chunkSize, cipher);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SecureCommunicationHandler nextStage(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
        try {
            if (checkExpectation(httpRequest)) {
                // ok now we generated a 2-way key and send it
                SecretKey secretKey = KeyGenerator.getInstance("DES").generateKey();
                writeKeyToClient(httpResponse, secretKey);
                return new SymetricSecureCommunicationHandlerImpl(secretKey, getChunkSize(), Cipher.getInstance("DES"));
            } else {
                return expectationFailed(httpResponse);
            }
        } catch (InvalidKeyException e) {
            getLogger().warn("Cannot use the private key", e);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        return this;
    }

}
